import React, {useState, useEffect, useRef} from 'react';
import {connect} from 'react-redux';
import {
  SafeAreaView,
  Alert,
  ScrollView,
  View,
  Text,
  Image,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  RefreshControl,
  Dimensions,
  ActivityIndicator,
} from 'react-native';
import {Button, Icon, Tab, TabView} from '@rneui/themed';
import Overlay from '@/components/Overlay';
import {setUserInfo, setAuth} from '@/store/action/user';
import {getAndroidMsgList, updateAndroidMsgState} from '@/apis/api';
import {useFocusEffect} from '@react-navigation/native';
import {formatDate} from '@/utils';
import {useTranslation} from 'react-i18next';

const size = s => (Dimensions.get('window').width / 375) * s;
function Form(props: any) {
  const {t} = useTranslation();
  let [list, setList] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false); // 不用
  let [refreshingAll, setRefreshingAll] = useState(false);

  let [total, setTotal] = useState(0);
  const [showBtn, setShowBtn] = useState(false);
  const [pageNum, setPageNum] = useState(1);
  const scrollViewRef = useRef();
  const [tabIndex, setTabIndex] = React.useState(0);

  let flat = null;

  const handleTabChange = (tabIndex: number) => {
    setTabIndex(tabIndex);
    if (tabIndex === 0) {
      onRefresh();
    } else {
      onRefreshUnread();
    }
  };

  // 未读消息
  let [refreshingUnread, setRefreshingUnread] = useState(false);
  let [unreadPageNum, setUnreadPageNum] = useState(1);
  let [unreadTotal, setUnreadTotal] = useState(0);
  let [unreadList, setUnreadList] = useState([]);
  let unreadFlat = null;
  // 获取未读消息列表
  const getUnreadMsgList = (loadMore: boolean = false) => {
    let actualPageNum = unreadPageNum;
    if (loadMore) {
      actualPageNum = unreadPageNum + 1;
      setUnreadPageNum(actualPageNum);
    }
    const param = {
      pageNum: actualPageNum,
      pageSize: 15,
      state: 0, // 未读
    };
    setIsLoading(true);
    getAndroidMsgList(param)
      .then(res => {
        const msgList = res?.data?.list || [];
        setUnreadTotal(res.data.total || 0);
        if (loadMore) {
          let data = [...unreadList];
          setUnreadList([...data, ...msgList]);
        } else {
          setUnreadList(msgList);
        }
      })
      .finally(() => {
        setIsLoading(false);
      });
  };

  const handleLoadMoreUnread = () => {
    if (unreadList.length < 15) {
      return false;
    } else {
      if (unreadList.length !== unreadTotal) {
        getUnreadMsgList(true);
      }
    }
  };

  //  未读消息下拉刷新
  const onRefreshUnread = async () => {
    setRefreshingUnread(true);
    setUnreadPageNum(1);
    const param = {
      pageNum: 1,
      pageSize: 15,
      state: 0,
    };
    // 获取消息列表
    getAndroidMsgList(param).then(res => {
      const msgList = res?.data?.list || [];
      setUnreadTotal(res.data.total || 0);
      setUnreadList(msgList);
      setRefreshingUnread(false);
    });
  };
  useFocusEffect(
    React.useCallback(() => {
      setTabIndex(0);
      getMsgList();
      return () => {
      };
    }, []),
  );

  useEffect(() => {
  }, []);
  const getMsgList = (loadMore: boolean = false) => {
    let actualPageNum = pageNum;
    if (loadMore) {
      actualPageNum = pageNum + 1;
      setPageNum(actualPageNum);
    }
    const param = {
      pageNum: actualPageNum,
      pageSize: 15,
    };
    // 获取消息列表
    setIsLoading(true);
    getAndroidMsgList(param)
      .then(res => {
        const msgList = res?.data?.list || [];
        setTotal(res.data.total || 0);
        if (loadMore) {
          let data = [...list];
          setList([...data, ...msgList]);
        } else {
          setList(msgList);
        }
      })
      .finally(() => {
        setIsLoading(false);
      });
  };
  const onDetail = (data, dataIndex) => {
    Alert.alert(formatDate(data.createTime, 'yyyy-MM-dd HH:mm'), data.content, [
      {
        text: t('sys_close'),
        onPress: () => {},
      },
    ]);
    if (data.state === 1) return;
    const params = {
      noticeId: data.noticeId,
      state: 1,
    };
    updateAndroidMsgState(params);
    if (tabIndex === 0) {
      const listData = [...list];
      listData[dataIndex].state = 1;
      setList(listData);
    } else {
      const listData = [...unreadList];
      listData[dataIndex].state = 1;
      setUnreadList(listData);
    }
  };
  const handleLoadMore = () => {
    if (list.length < 15) {
      return false;
    } else {
      if (list.length !== total) {
        getMsgList(true);
      }
    }
  };

  const handleOnScroll = e => {
    setShowBtn(e.nativeEvent.contentOffset.y > 1000);
  };
  //      下拉刷新
  const onRefresh = async () => {
    setRefreshingAll(true);
    setPageNum(1);
    const param = {
      pageNum: 1,
      pageSize: 15,
    };
    // 获取消息列表
    getAndroidMsgList(param).then(res => {
      const msgList = res?.data?.list || [];
      setTotal(res.data.total || 0);
      setList(msgList);
      setRefreshingAll(false);
    });
  };

  function handleRefresh() {
    setRefreshing(true);
  }

  const ListFooter = ({list = [], total = 0}) => {
    if (list.length == 0) {
      return null;
    } else if (list.length === total) {
      if (list.length === total) {
        return (
          <View style={{paddingTop: 20, paddingBottom: 15}}>
            <Text style={{color: '#ccc', fontSize: 12, textAlign: 'center'}}>
              {t('sys_finishLoadData')}
            </Text>
          </View>
        );
      } else {
        return null;
      }
    } else {
      return (
        <View
          style={{
            paddingVertical: 20,
            alignItems: 'center',
          }}>
          <Text>{t('sys_loadMore')}</Text>
        </View>
      );
    }
  };

  const ListUnreadFooter = ({unreadList = [], unreadTotal = 0}) => {
    if (unreadList.length == 0) {
      return null;
    } else if (unreadList.length === unreadTotal) {
      if (unreadList.length === unreadTotal) {
        return (
          <View style={{paddingTop: 20, paddingBottom: 15}}>
            <Text style={{color: '#ccc', fontSize: 12, textAlign: 'center'}}>
              {t('sys_finishLoadData')}
            </Text>
          </View>
        );
      } else {
        return null;
      }
    } else {
      return (
        <View
          style={{
            paddingVertical: 20,
            alignItems: 'center',
          }}>
          <Text>{t('sys_loadMore')}</Text>
        </View>
      );
    }
  };
  const ListEmptyComponent = () => {
    return (
      <View
        style={{
          flex: 1,
          alignItems: 'center',
          justifyContent: 'center',
          marginTop: 200,
        }}>
        <Text style={{fontSize: 12, color: '#999'}}>暂无消息</Text>
      </View>
    );
  };
  const handleScroll = () => {
    if (tabIndex === 0) {
      flat.scrollToOffset({animated: true, viewPosition: 0, index: 0});
    } else {
      unreadFlat.scrollToOffset({animated: true, viewPosition: 0, index: 0});
    }
  };

  return (
    <SafeAreaView style={styles.flex}>
      <Overlay isShow={isLoading} />
      <View style={styles.flex}>
        <Tab
          value={tabIndex}
          onChange={handleTabChange}
          indicatorStyle={{
            backgroundColor: '#1677ff',
            height: 4,
          }}
          variant="primary">
          <Tab.Item title={t('sys_allMessage')} titleStyle={{fontSize: 12}} />
          <Tab.Item title={t('sys_unreadMessage')} titleStyle={{fontSize: 12}} />
        </Tab>
        <TabView value={tabIndex} onChange={setTabIndex} animationType="spring">
          <TabView.Item style={{width: '100%'}}>
            <FlatList
              ref={flatList => {
                flat = flatList;
              }}
              keyExtractor={(item, index) => index.toString()}
              data={list}
              refreshControl={
                <RefreshControl
                  refreshing={refreshingAll}
                  onRefresh={onRefresh}
                  tintColor={'#0078ff'}
                />
              }
              renderItem={({item, index}) => (
                <TouchableOpacity onPress={() => onDetail(item, index)}>
                  <View
                    style={[
                      styles.listItem,
                      {borderBottomWidth: list.length == index + 1 ? 0 : 1},
                    ]}>
                    {/* <View style={styles.msgIcon}>
                  <Image source={ArrowIcon} style={styles.image} />
                </View> */}
                    <View style={styles.listItemRight}>
                      <View
                        style={{
                          flexDirection: 'row',
                          justifyContent: 'space-between',
                        }}>
                        <View style={styles.listItemRightTop}>
                          <Text
                            style={styles.listItemRightTopText}
                            numberOfLines={2}>
                            {index + 1}. {item.content}
                          </Text>
                        </View>
                        <View
                          style={{
                            flexDirection: 'row',
                            padding: 4,
                            justifyContent: 'center',
                            alignItems: 'center',
                          }}>
                          <Text style={styles.createAt}>
                            {formatDate(item.createTime, 'yyyy-MM-dd HH:mm')}
                          </Text>
                        </View>
                        <View
                          style={{
                            flexDirection: 'row',
                            padding: 4,
                            justifyContent: 'center',
                            alignItems: 'center',
                          }}>
                          {!item.state ? (
                            <View style={styles.readStatus}></View>
                          ) : (
                            <View style={styles.noreadStatus}></View>
                          )}
                        </View>
                      </View>
                    </View>
                  </View>
                </TouchableOpacity>
              )}
              ListFooterComponent={() => ListFooter({list, total})}
              onRefresh={handleRefresh}
              refreshing={refreshing}
              onEndReached={handleLoadMore}
              onEndReachedThreshold={0.1}
              onScroll={handleOnScroll}
              ListEmptyComponent={() => ListEmptyComponent()}
            />
          </TabView.Item>
          <TabView.Item style={{width: '100%'}}>
            {/* 未读消息 */}
            <FlatList
              ref={flatList => {
                unreadFlat = flatList;
              }}
              keyExtractor={(item, index) => index.toString()}
              data={unreadList}
              refreshControl={
                <RefreshControl
                  refreshing={refreshingUnread}
                  onRefresh={onRefreshUnread}
                  tintColor={'#0078ff'}
                />
              }
              renderItem={({item, index}) => (
                <TouchableOpacity onPress={() => onDetail(item, index)}>
                  <View
                    style={[
                      styles.listItem,
                      {borderBottomWidth: list.length == index + 1 ? 0 : 1},
                    ]}>
                    <View style={styles.listItemRight}>
                      <View
                        style={{
                          flexDirection: 'row',
                          justifyContent: 'space-between',
                        }}>
                        <View style={styles.listItemRightTop}>
                          <Text
                            style={styles.listItemRightTopText}
                            numberOfLines={2}>
                            {index + 1}. {item.content}
                          </Text>
                        </View>
                        <View
                          style={{
                            flexDirection: 'row',
                            padding: 4,
                            justifyContent: 'center',
                            alignItems: 'center',
                          }}>
                          <Text style={styles.createAt}>
                            {formatDate(item.createTime, 'yyyy-MM-dd HH:mm')}
                          </Text>
                        </View>
                        <View
                          style={{
                            flexDirection: 'row',
                            padding: 4,
                            justifyContent: 'center',
                            alignItems: 'center',
                          }}>
                          {!item.state ? (
                            <View style={styles.readStatus}></View>
                          ) : (
                            <View style={styles.noreadStatus}></View>
                          )}
                        </View>
                      </View>
                    </View>
                  </View>
                </TouchableOpacity>
              )}
              ListFooterComponent={() =>
                ListUnreadFooter({unreadList, unreadTotal})
              }
              onRefresh={handleRefresh}
              refreshing={refreshing}
              onEndReached={handleLoadMoreUnread}
              onEndReachedThreshold={0.1}
              onScroll={handleOnScroll}
              ListEmptyComponent={() => ListEmptyComponent()}
            />
          </TabView.Item>
        </TabView>
      </View>
      {showBtn ? (
        <TouchableOpacity
          onPress={handleScroll}
          activeOpacity={0.7}
          style={{
            position: 'absolute',
            bottom: size(10),
            right: size(20),
            backgroundColor: '#1677ff',
            padding: size(10),
            borderRadius: size(20),
          }}>
          <Icon color="#fff" size={size(20)} name="arrowup" type="antdesign" />
        </TouchableOpacity>
      ) : null}
    </SafeAreaView>
  );
}
export default connect(
  (state: any) => ({
    userInfo: state.user.userInfo,
    auth: state.user.auth,
  }),
  dispatch => ({
    setUserInfo: (data: any) => dispatch(setUserInfo(data)),
    setAuth: (token: any) => dispatch(setAuth(token)),
  }),
)(Form);
const styles = StyleSheet.create({
  flex: {
    flex: 1,
    backgroundColor: '#fff',
  },
  listItem: {
    flexDirection: 'row',
    alignItems: 'center',
    flexWrap: 'wrap',
    backgroundColor: '#fff',
    padding: 5,
    marginTop: 5,
    borderRadius: 5,
    borderBottomColor: '#E5E5E5',
    borderStyle: 'solid',
  },
  listItemRight: {
    flex: 1,
    flexDirection: 'column',
    paddingLeft: 10,
    paddingRight: 10,
    marginTop: 5,
    marginBottom: 5,
  },
  listItemRightTop: {
    flex: 1,
  },
  listItemRightFooterText: {
    textAlign: 'right',
    color: '#999',
    marginTop: 5,
    fontSize: 12,
  },
  listItemRightTopText: {
    lineHeight: 20,
    fontSize: 16,
  },
  msgIcon: {
    width: size(30),
    height: size(30),
    // backgroundColor: '#f9f9f9',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: size(8),
  },

  borderStyle: {
    borderColor: '#cacaca',
    borderWidth: 1,
  },

  createAt: {
    marginLeft: 4,
    fontSize: 11,
    color: '#BFBFBF',
  },
  readStatus: {
    width: 10,
    height: 10,
    backgroundColor: '#ff4d4f',
    borderRadius: 5,
  },
  noreadStatus: {
    width: 10,
    height: 10,
  },
  activity: {
    marginBottom: 5,
  },
});
